<?php
namespace App\Http\Controllers\Api;

use App\Http\Models\Renting;
use GuzzleHttp;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller{
    public function login(Request $request){

        #方法一:
        try{
            $this->validate($request,[
                'username' =>'required',
                'password'=> 'required'
            ]);
        }catch (\Exception $e){
            return ['status'=>1000, 'msg'=>'账号密码不能欸空'];
        }

//        dump(auth()->guard('apiuser'));
        $bool = auth()->guard('apiuser')->attempt($request->all());
        if($bool){
            //生成token
            $userModel = auth()->guard('apiuser')->user();
            //判断接口当天是否超过2000次
            if($userModel->click > env('APINUM')){
                return response()->json(['status'=>1002,'msg'=>'当天请求次数上限'],500);
            }
            //生成token 保存在服务器端一份 给客户端一份
            $token = $userModel->createToken('api')->accessToken;
            //当请求次数加一
            $userModel->increment('click');
            $data = [
                'expire'=>7200,
                'token'=> $token
            ];
            return response()->json($data);
        }else{
            return response()->json(['status'=>1001,'msg'=>'账号或者密码不正确'],401);
        }

        #方法二:去存储中验证

    }

    public function wxlogin(Request $request){
        $appid = 'wx13248c100beb3217';
        $secret = '4c8bee277e56fdd3fa8e1a028f094b74';
        //小程序传来的
        $code = $request->get('code');
        //请求地址
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $url = sprintf($url,$appid,$secret,$code);
        //申请请求客户端 verify 不检查证书ssl
        $client = new GuzzleHttp\Client(['timeout'=>5,'verify'=> false]);
        $reponse = $client->get($url);
        $ret = (string)$reponse->getBody();

        //json转成数组
        $arr = json_decode($ret,true);
        //写到数据表中
        try {
            Renting::create(['openid'=>$arr['openid']]);
        }catch(\Exception $exception){

        }


        return $ret;

    }
}
